#include <iostream>
#include <string>
#include <pthread.h>
#include <functional>
#include <memory> // 用于智能指针

namespace ThreadModule
{
    using func_t = std::function<void(const std::string &)>;

    class Thread
    {
    private:
        pthread_t _tid;
        std::string _threadname;
        func_t _func;
        bool _stop;

    public:
        Thread(func_t func, const std::string threadname = "default name")
            : _func(func), _threadname(threadname), _stop(true) {}

        ~Thread() {}
        std::string name()
        {
            return _threadname;
        }
        void Execute()
        {
            // _func(_data,_threadname);
            _func(_threadname);
        }

        static void *threadroutine(void *args)
        {
            Thread *self = static_cast<Thread *>(args);
            self->Execute();
            return nullptr;
        }

        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, threadroutine, this);
            if (n == 0)
            {
                _stop = false;
                return true;
            }
            else
            {
                return false;
            }
        }

        void Detach()
        {
            if (!_stop)
            {
                pthread_detach(_tid);
            }
        }

        void Join()
        {
            if (!_stop)
            {
                pthread_join(_tid, nullptr);
            }
        }

        void Stop()
        {
            _stop = true;
        }
    };
}